import axios from "axios";
import { Loading } from "element-ui";
import Vue from "vue";
import router from "../router/index";
let vm = new Vue();

let loading = null;

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    loading = Loading.service({
      background: "rgba(0,0,0,0.5)",
    });

    // config.baseURL = base_url;
    config.baseURL = "/api";

    config.headers.token =
      localStorage.getItem("token") != null
        ? localStorage.getItem("token")
        : "";
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    loading.close();

    //错误code码

    if (response.data.code === 1) {
      vm.$message({
        message: response.data.msg,
        type: "error",
      });
      return Promise.reject();
    }

    // catch error
    const errCodes = [1, 401, 403, 500, 999];

    if (errCodes.indexOf(response.data.code) != -1) {
      vm.$message({
        message: response.data.msg,
        type: "error",
      });
      return response.data;
    }

    //重新登陆
    if (response.data.code === 100) {
      vm.$message({
        message: response.data.msg,
        type: "error",
      });
      return router.replace("/login");
      // return router.push('/login').catch(err => { console.log(err) })
    } else {
      return response.data;
    }
  },
  function (error) {
    // 对响应错误做点什么

    loading.close();

    return Promise.reject(error);
  }
);

const get = (url, data) => {
  return axios({
    method: "get",
    url: url,
    params: data,
  });
};

const post = (url, data) => {
  return axios({
    method: "post",
    url: url,
    data,
  });
};

export { get, post };
